using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.IO;

namespace PrGrSerwerRozproszony
{
    class UserToServerConnection : IConnection
    {
        private int userId;
        private MainLoop.RemoveUserFromListDelegate removeUserFromListDelegate;
        private MainLoop.SendMessageToUserDelegate sendMessageToUserDelegate;
        private TcpClient tcpClient;
        private bool isRunning = true;

        public UserToServerConnection(int userId, MainLoop.RemoveUserFromListDelegate removeUserFromListDelegate,
                        MainLoop.SendMessageToUserDelegate sendMessageToUserDelegate)
        {
            this.userId = userId;
            this.removeUserFromListDelegate = removeUserFromListDelegate;
            this.sendMessageToUserDelegate = sendMessageToUserDelegate;
        }

        #region IConnection Members

        public TcpClient TcpClient
        {
            set { tcpClient = value; ; }
        }

        public void Start()
        {
            new Thread(new ParameterizedThreadStart(this.Run)).Start(null);
        }

        StreamWriter streamWriter = null; 
        public void Run(object obj)
        {
            try
            {
                NetworkStream networkStream = tcpClient.GetStream();
                StreamReader reader = new StreamReader(networkStream);
                streamWriter = new StreamWriter(networkStream);

                while (isRunning)
                {
                    string line = reader.ReadLine();
                    int userIdToSend = int.Parse(line.Split(MainLoop.DELIMETER)[1]);

                    Console.WriteLine("READ MSG: " + line);

                    sendMessageToUserDelegate(userIdToSend, line, true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            removeUserFromListDelegate(userId);
        }

        public void SendMessage(string msg)
        {
            try
            {
                streamWriter.WriteLine(msg);
                streamWriter.Flush();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                isRunning = false;
            }
        }

        #endregion
    }
}
